<template>
  <div class="movie-detail" v-loading="loading">
    <el-page-header @back="goBack" class="page-header"></el-page-header>

    <el-card v-if="movie" class="movie-card-detail">
      <el-row>
        <el-col :span="24">
          <h2>{{ movie.title }}</h2>
          <el-descriptions :column="2" border class="movie-info-descriptions">
            <el-descriptions-item label="导演">{{ movie.director || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="状态">{{ movie.status || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="类型">{{ movie.genre || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="上映日期">{{ movie.releaseDate || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="片长">{{ movie.duration ? `${movie.duration} 分钟` : '未知' }}</el-descriptions-item>
            <el-descriptions-item label="演员" :span="2">{{ movie.actors || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="简介" :span="2">{{ movie.description || '暂无简介' }}</el-descriptions-item>
          </el-descriptions>

          <!-- 移除购票按钮 -->
          <div class="action-buttons">
             <!-- 购票按钮已移除 -->
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-empty v-if="error" description="加载电影信息失败"></el-empty>

    <!-- TODO: 添加排片列表组件 -->
    <!-- <MovieShowtimes :movieId="movieId" /> -->
    <!-- 修改：添加场次显示区域 -->
    <div class="showtimes-section" ref="showtimesSectionRef" v-loading="loadingShowtimes">
      <h3>场次信息</h3>
      <el-empty v-if="!loadingShowtimes && showtimes.length === 0" description="暂无可用场次"></el-empty>
      <el-table v-else :data="showtimes" style="width: 100%">
        <el-table-column prop="showTime" label="放映时间">
          <template #default="scope">
            {{ formatShowtime(scope.row.showTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="hallName" label="影厅" />
        <el-table-column prop="price" label="价格">
           <template #default="scope">
             ¥{{ scope.row.price?.toFixed(2) }}
           </template>
        </el-table-column>
        <el-table-column prop="availableSeats" label="余票" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="selectShowtime(scope.row)"
              :disabled="new Date() > new Date(scope.row.showTime)"
            >
              {{ new Date() > new Date(scope.row.showTime) ? '购票已结束' : '选座购票' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 评论区 -->
    <div class="reviews-section" v-loading="loadingReviews">
      <h3>用户评论
        <el-button type="primary" size="small" icon="Refresh" circle @click="refreshReviews"
          style="float: right; margin-top: 2px;" title="刷新评论列表"></el-button>
      </h3>
      <el-empty v-if="reviews.length === 0 && !loadingReviews" description="暂无评论"></el-empty>
      <div v-else>
        <!-- 循环显示所有评论 (排除当前用户的评论，如果已单独显示) -->
        <div v-for="review in reviews.filter(r => !userReview || r.id !== userReview.id)" :key="review.id" class="review-item">
          <!-- Left Part: User Info -->
          <div class="review-user">
            <span>用户: {{ review.user?.username || '未知用户' }}</span>
          </div>
          <!-- Middle Part: Comment -->
          <p class="review-comment">{{ review.comment }}</p>
          <!-- Right Part: Meta Info -->
          <div class="review-meta">
            <span>{{ formatDateTime(review.reviewTime) }}</span>
            <el-rate v-model="review.rating" disabled show-score text-color="#ff9900" score-template="{value} 分" class="review-rating" size="small" />
          </div>
        </div>
      </div>

      <!-- 根据登录和评论状态显示不同内容 -->
      <!-- 1. 用户已登录 -->
      <div v-if="userStore.isLoggedIn" style="margin-top: 30px;">
        <!-- 1a. 用户尚未评论 或 正在编辑评论 -> 显示表单 -->
        <el-card class="add-review-card" v-if="!userReview || isEditing">
            <h4>{{ isEditing ? '编辑您的评论' : '发表评论' }}</h4>
            <el-form :model="newReview" ref="reviewFormRef" label-position="top">
                <el-form-item label="评分" prop="rating">
                    <el-rate v-model="newReview.rating" :max="5" show-score text-color="#ff9900"></el-rate>
                </el-form-item>
                <el-form-item label="评论内容" prop="comment">
                    <el-input v-model="newReview.comment" type="textarea" :rows="4" placeholder="写下你的看法..."></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitReview" :loading="submittingReview">
                      {{ isEditing ? '更新评论' : '提交评论' }}
                    </el-button>
                    <el-button v-if="isEditing" @click="cancelEdit">取消编辑</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 1b. 用户已评论且未在编辑 -> 显示评论及按钮 -->
        <el-card class="user-review-display" v-else-if="userReview && !isEditing">
             <h4>您的评论</h4>
             <div class="review-item" style="border-bottom: none; margin-bottom: 0; padding-bottom: 0;">
               <div class="review-header">
                 <div class="review-meta">
                   <span>{{ formatDateTime(userReview.reviewTime) }}</span>
                   <el-rate v-model="userReview.rating" disabled show-score text-color="#ff9900" score-template="{value} 分" class="review-rating" size="small" />
                 </div>
               </div>
               <p class="review-comment" style="margin-top: 10px;">{{ userReview.comment }}</p>
               <div style="text-align: right; margin-top: 15px;">
                   <el-button type="primary" size="small" @click="editReview">编辑</el-button>
                   <el-button type="danger" size="small" @click="deleteUserReview">删除</el-button>
               </div>
             </div>
        </el-card>
      </div>
      <!-- 2. 用户未登录 -> 显示登录提示 -->
      <div v-else class="login-prompt" style="margin-top: 30px;">
          请 <router-link :to="{ name: 'Login', query: { redirect: route.fullPath } }">登录</router-link> 后发表评论。
      </div>

    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axiosInstance from '../utils/axiosInstance';
import { ElMessage, ElIcon, ElPageHeader, ElCard, ElRow, ElCol, ElImage, ElDescriptions, ElDescriptionsItem, ElEmpty, ElButton, ElRate, ElInput, ElForm, ElFormItem, ElMessageBox } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { Picture, Refresh } from '@element-plus/icons-vue';
import { useUserStore } from '../store/user';

// 定义 Movie 类型接口 (与 Home.vue 保持一致)
interface Movie {
  id: number;
  title: string;
  director?: string;
  actors?: string;
  genre?: string;
  releaseDate?: string;
  duration?: number;
  description?: string;
  status?: string;
}

// 新增：定义 Showtime 类型接口
interface Showtime {
  id: number;
  movieId: number;
  hallName: string;
  showTime: string; // 后端是 LocalDateTime，前端接收为 string
  price: number;
  availableSeats: number;
}

// 定义 Review 类型接口
interface Review {
  id: number;
  userId: number;
  // userName?: string; // 最好后端关联查询用户名
  // 修改：添加 user 对象以接收关联信息
  user?: {
    id: number;
    username: string;
  };
  movieId: number;
  rating: number;
  comment: string;
  reviewTime: string; // 或 Date
}

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

const movie = ref<Movie | null>(null);
const loading = ref(true);
const loadingReviews = ref(false);
const error = ref<string | null>(null);
const movieId = ref<number | null>(null);
const reviews = ref<Review[]>([]); // 添加评论数组
const showtimes = ref<Showtime[]>([]); // 新增：场次数组
const loadingShowtimes = ref(false);   // 新增：加载场次状态
const showtimesSectionRef = ref<HTMLElement | null>(null); // 新增：场次区域引用

// 新增状态变量
const userReview = ref<Review | null>(null); // 存储当前用户的评论
const isEditing = ref(false); // 标记是否处于编辑模式

// 评论表单相关
const reviewFormRef = ref<FormInstance>();
const submittingReview = ref(false);
const newReview = reactive({
    rating: 0,
    comment: ''
});

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
};

// 新增：格式化场次时间 (只显示时分)
const formatShowtime = (dateString: string) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  // 获取月日
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  // 获取时分
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${month}-${day} ${hours}:${minutes}`;
};

const fetchReviews = async () => {
  if (!movieId.value) return;
  loadingReviews.value = true;
  userReview.value = null; // 重置用户评论状态
  isEditing.value = false; // 重置编辑状态
  try {
    const response = await axiosInstance.get<Review[]>(`/movies/${movieId.value}/reviews`);
    reviews.value = response.data;

    // 检查当前用户是否已评论
    const currentUserId = userStore.user?.id; // 安全访问用户ID
    if (currentUserId && reviews.value.length > 0) {
      userReview.value = reviews.value.find(review => review.userId === currentUserId) || null;
    }

  } catch (err) {
    console.error("Failed to fetch reviews:", err);
    ElMessage.error('加载评论列表失败');
  } finally {
    loadingReviews.value = false;
  }
};

// 新增：获取场次信息的方法
const fetchShowtimes = async () => {
  if (!movieId.value) return;
  loadingShowtimes.value = true;
  try {
    const response = await axiosInstance.get<Showtime[]>(`/movies/${movieId.value}/showtimes`);
    showtimes.value = response.data;
  } catch (err) {
    console.error("Failed to fetch showtimes:", err);
    ElMessage.error('加载场次信息失败');
  } finally {
    loadingShowtimes.value = false;
  }
};

const fetchMovieDetail = async () => {
  const idParam = route.params.id;
  if (!idParam) {
    error.value = "无效的电影ID";
    ElMessage.error('未找到电影ID');
    return;
  }
  movieId.value = Number(idParam);
  if (isNaN(movieId.value)) {
    error.value = "无效的电影ID格式";
    ElMessage.error('电影ID格式错误');
    return;
  }

  loading.value = true;
  error.value = null;
  try {
    const response = await axiosInstance.get<Movie>(`/movies/${movieId.value}`);
    movie.value = response.data;
    // 获取电影详情成功后，获取评论和场次
    await Promise.all([
        fetchReviews(),
        fetchShowtimes() // 调用获取场次信息
    ]);
  } catch (err: any) {
    console.error(`Failed to fetch movie ${movieId.value}:`, err);
    error.value = "加载电影详情失败";
    // 错误消息已由 axios 拦截器处理，这里只记录日志和设置错误状态
    // ElMessage.error('加载电影详情失败');
  } finally {
    loading.value = false;
  }
};

// 手动刷新评论列表
const refreshReviews = async () => {
  await fetchReviews();
  ElMessage.success('评论列表已刷新');
};

// 监听路由参数变化，确保切换电影时重新加载评论
watch(() => route.params.id, (newId) => {
  if (newId) {
    fetchMovieDetail();
  }
}, { immediate: true });

const goBack = () => {
  router.back();
};

// const editMovie = () => {
//   // 跳转到编辑页面，或打开编辑弹窗
//   router.push({ name: 'AdminMovieEdit', params: { id: movieId.value } });
// };

// const buyTicket = () => {
//   // 处理购票逻辑，可能需要结合排片信息
//   ElMessage.info('购票功能待实现');
// };

// 添加编辑和取消编辑函数
const editReview = () => {
  if (userReview.value) {
    newReview.rating = userReview.value.rating;
    newReview.comment = userReview.value.comment;
    isEditing.value = true;
  }
};

const cancelEdit = () => {
  isEditing.value = false;
  newReview.rating = 0;
  newReview.comment = '';
};

// 添加更新评论函数
const updateReview = async () => {
    if (!movieId.value || !userReview.value) {
        console.error('UpdateReview called without movieId or userReview');
        return;
    }
    if (!reviewFormRef.value) return;

    await reviewFormRef.value.validate(async (valid) => {
        if (valid) {
            if (newReview.rating === 0) {
                ElMessage.warning('请选择评分');
                return;
            }
            submittingReview.value = true;
            try {
                await axiosInstance.put(`/reviews/${userReview.value!.id}`, {
                    rating: newReview.rating,
                    comment: newReview.comment,
                    movieId: movieId.value
                });
                ElMessage.success('评论更新成功！');
                newReview.rating = 0;
                newReview.comment = '';
                isEditing.value = false;
                await fetchReviews();
            } catch (err) {
                console.error("Failed to update review:", err);
            } finally {
                submittingReview.value = false;
            }
        }
    });
};

// 修改提交评论函数
const submitReview = async () => {
    if (isEditing.value) {
      await updateReview();
    } else {
      if (userReview.value) {
          ElMessage.warning('您已经评论过这部电影了，不能重复提交。');
          return;
      }

      if (!movieId.value) return;
      if (!reviewFormRef.value) return;

      await reviewFormRef.value.validate(async (valid) => {
          if (valid) {
              if (newReview.rating === 0) {
                  ElMessage.warning('请选择评分');
                  return;
              }
              submittingReview.value = true;
              try {
                  const response = await axiosInstance.post(`/movies/${movieId.value}/reviews`, {
                      rating: newReview.rating,
                      comment: newReview.comment
                  });
                  ElMessage.success('评论发表成功！');
                  newReview.rating = 0;
                  newReview.comment = '';
                  await fetchReviews();
              } catch (err: any) {
                  console.error("Failed to submit review:", err);
                  if (err.response && err.response.status === 409) {
                       ElMessage.warning('您已经评论过这部电影了。');
                       await fetchReviews();
                  }
              } finally {
                  submittingReview.value = false;
              }
          }
      });
    }
};

// --- 添加删除评论函数 ---
const deleteUserReview = async () => {
    if (!userReview.value) return;

    try {
        await ElMessageBox.confirm(
            '确定要删除您的评论吗？此操作不可恢复。',
            '删除确认',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );

        // 用户确认删除，调用后端删除接口
        await axiosInstance.delete(`/reviews/${userReview.value.id}`);
        ElMessage.success('评论已删除');

        // 删除成功后，刷新评论列表
        // 这会自动将 userReview 设置为 null，从而显示"发表评论"表单
        await fetchReviews();

    } catch (error: any) {
        if (error === 'cancel') {
            // 用户点击了取消，不做任何事
            return;
        }
        console.error("Failed to delete review:", error);
        // 错误消息由拦截器处理
        // ElMessage.error('删除评论失败');
    }
};
// --- 结束添加删除评论函数 ---

// 新增：滚动到场次区域
const scrollToShowtimes = () => {
  showtimesSectionRef.value?.scrollIntoView({ behavior: 'smooth' });
};

// 处理选座购票点击，跳转到选座页面
const selectShowtime = (showtime: Showtime) => {
  console.log('Selected showtime:', showtime);
  // 跳转到选座页面
  router.push({
    name: 'SeatSelection',
    params: { showtimeId: showtime.id }
  });
};

onMounted(() => {
  fetchMovieDetail();
});
</script>

<style scoped>
.movie-detail {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.movie-card-detail {
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.9); /* Semi-transparent white */
  border-radius: 8px; /* Ensure border-radius */
}

h2 {
  margin-top: 0;
  margin-bottom: 20px;
}

.movie-info-descriptions {
  margin-bottom: 20px;
}

.action-buttons {
  margin-top: 20px;
  text-align: right;
}

.showtimes-section {
  margin-top: 30px;
  /* background-color: #fff; */
  background-color: rgba(255, 255, 255, 0.85);
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}

.showtimes-section h3 {
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.reviews-section {
  margin-top: 30px;
  /* background-color: #fff; */
  background-color: rgba(255, 255, 255, 0.85);
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}

.reviews-section h3 {
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.review-item {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #eee;
  display: flex;
  align-items: baseline;
  gap: 15px;
}

.review-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.review-user {
  color: #606266;
  font-size: 0.9rem;
  flex-shrink: 0;
  width: 150px;
}

.review-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  font-size: 0.9rem;
  color: #606266;
  flex-shrink: 0;
  width: 180px;
}

.review-rating {
  margin-left: 0;
  margin-top: 4px;
}

.review-comment {
  color: #303133;
  line-height: 1.6;
  flex-grow: 1;
  text-align: center;
  margin: 0;
}

.add-review-card,
.user-review-display {
    margin-top: 30px;
    background-color: rgba(255, 255, 255, 0.9); /* Semi-transparent */
}

.login-prompt {
    margin-top: 20px;
    padding: 15px;
    background-color: #f0f9eb;
    border: 1px solid #e1f3d8;
    border-radius: 4px;
    color: #67c23a;
    text-align: center;
}

.login-prompt a {
    color: #409EFF;
    text-decoration: none;
    font-weight: bold;
}
.login-prompt a:hover {
    text-decoration: underline;
}

/* Style el-page-header back button */
:deep(.el-page-header__left) {
  /* Remove default styles if any */
  margin-right: 0; /* Remove any potential margin causing the divider space */
}

/* Hide the vertical divider */
:deep(.el-page-header__left .el-divider--vertical) {
    display: none;
}

:deep(.el-page-header__back) {
  background-color: #409EFF; /* Blue background */
  color: white !important; /* White text */
  padding: 6px 12px; /* Button padding */
  border-radius: 4px; /* Rounded corners */
  transition: background-color 0.3s;
  text-decoration: none; /* Remove underline */
}

:deep(.el-page-header__back .el-icon) {
    color: white !important; /* Ensure icon is white */
    vertical-align: middle; /* Align icon nicely */
}

:deep(.el-page-header__back .el-page-header__title) {
    color: white !important; /* Ensure text is white */
    vertical-align: middle; /* Align text nicely */
}

:deep(.el-page-header__back:hover) {
  background-color: #66b1ff; /* Lighter blue on hover */
}

</style>